import React, { useState, useRef } from "react";
import Popover from "components/Popover";
import { addPrize, deletePrize } from "api/backend";
import garbageBox from "assets/img/garbageBox.svg";
import "./index.less";

export default function AddPrize() {
  const [prizeName, setPrizeName] = useState("");
  const [photoVisible, setPhotoVisible] = useState(false);
  const [photo, setPhoto] = useState("");
  const [message, setMessage] = useState("");
  const [popVisible, setPopVisible] = useState(false);
  const [popTitle, setPopTitle] = useState("");
  const fileRef = useRef();

  // 获取图片信息
  const getPhotoFile = (e) => {
    e.preventDefault();
    let reader = new FileReader();
    // 避免添加图片后，重新添加图片的bug
    if(e.target.files.length === 0) return;
    let file = e.target.files[0];

    reader.onloadend = () => {
      // console.log("文件名为—", file);
      // console.log("文件结果为—", reader.result);
      fileRef.current = file;
      setPhoto(reader.result);
      setPhotoVisible(true);
    };

    reader.readAsDataURL(file);
  };

  // 上传奖品
  const upload = async () => {
    if (!prizeName || !fileRef.current) {
      setMessage("请添加有效信息");
      return;
    }
    const info = {
      prize_name: prizeName,
      prize_picture: fileRef.current,
    };
    setMessage("");
    await addPrize(info);
    setPopTitle("添加成功");
    setPopVisible(true);
  };

  // 拖拽奖品至垃圾箱
  const onDragOver = (e) => {
    e.preventDefault();
  };
  const onDropDelPrize = (e) => {
    // 从拖拽事件中获取传输过来的数据
    const info = JSON.parse(e.dataTransfer.getData("info"));
    const { id } = info;
    delPrizeHandle(id);
  };

  // 删除奖品
  const delPrizeHandle = async (id) => {
    await deletePrize(parseInt(id));
    setPopTitle("删除成功");
    setPopVisible(true);
  };

  // 确定按钮
  const ensureHandle = () => {
    setPopVisible(false);
    window.location.reload();
  };

  return (
    <>
      <div className="add-prize-container">
        <h1>创建奖品</h1>
        <div className="add-wrapper">
          <div className="prize-name-wrapper">
            <label htmlFor="prizeName">奖品名:</label>
            <input
              className="prize-name-input"
              type="text"
              id="prizeName"
              value={prizeName}
              onChange={(e) => setPrizeName(e.target.value)}
            />
          </div>
          <div className="prize-photo-wrapper">
            {photoVisible ? (
              <label htmlFor="prizePhoto">
                <img src={photo} alt="prizePhoto" style={{ width: "80px" }} />
              </label>
            ) : (
              <label className="upload" htmlFor="prizePhoto">
                +点击上传图片
              </label>
            )}
            <input
              id="prizePhoto"
              className="prize-photo-input"
              type="file"
              style={{ display: "none" }}
              onChange={getPhotoFile}
            />
          </div>
          {message && (
            <span className="add-message" style={{ marginRight: "20px" }}>
              {message}
            </span>
          )}
          <button className="upload-btn" onClick={upload}>
            确定上传
          </button>
        </div>
        <img
          onDrop={onDropDelPrize}
          onDragOver={onDragOver}
          draggable="false"
          className="garbage-box"
          src={garbageBox}
          alt="垃圾箱"
        />
      </div>
      <Popover
        appear={popVisible}
        title={popTitle}
        ensureHandle={ensureHandle}
      />
    </>
  );
}
